package com.humngyang.com.hmy.study.mywx.Util;

import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

public class HttpUtils {

    /**
     * Author : hmy
     *
     * @date 2020/3/20 22:44
     * describution : 发送get请求
     **/

    public static String get(String url) {
        String result = "";
        InputStream in = null;
        try {
            //打开和url的连接
            HttpURLConnection coon = (HttpURLConnection) new URL(url).openConnection();
            coon.setRequestProperty("accept", "*/*");
            coon.setRequestProperty("connection", "Keep-Alive");
            coon.setRequestProperty("Content-Type", "application/json");
            coon.setRequestProperty("Accept", "application/json");
            coon.setRequestMethod("GET");
            //建立实际的连接
            coon.connect();
            //定义输入流来读取url的响应
            in = coon.getInputStream();
            result = StreamUtils.copyToString(in, Charset.forName("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /**
     * Author : hmy
     *
     * @date 2020/3/20 22:57
     * describution :  发送post请求
     **/
    public static String post(String url, String paremeStr) {
        InputStream in = null;
        OutputStream os = null;
        String result = "";
        try {
            //打开和url的连接
            HttpURLConnection coon = (HttpURLConnection) new URL(url).openConnection();
            //设置请求属性
            coon.setRequestProperty("accept", "*/*");
            coon.setRequestProperty("connection", "Keep-Alive");
            //发送post请求需设置
            coon.setRequestMethod("POST");
            coon.setDoOutput(true);
            coon.setDoInput(true);
            os = coon.getOutputStream();
            //注意编码格式，防止中文乱码
            if (StringUtils.hasText(paremeStr)) {
                os.write(paremeStr.getBytes("utf-8"));
                os.close();
            }
            in = coon.getInputStream();
            result = StreamUtils.copyToString(in, Charset.forName("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}
